// let model = require('model.js');
// import emojimap from './emojimap.js'
// const emoji = emojimap.emojiList.emoji

// 日期格式化 type为1返回年月日时分秒，type为2返回年月日
const formatTime = (time, type) => {
  type = type || 1;

  var datetime = new Date();
  datetime.setTime(time * 1000);
  const year = datetime.getFullYear();
  const month = datetime.getMonth() + 1;
  const day = datetime.getDate();
  const hour = datetime.getHours();
  const minute = datetime.getMinutes();
  const second = datetime.getSeconds();

  if (type === 1) {
    console.log('formatNumber1是什么', formatNumber);
    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':');
  } else if (type === 2) {
    console.log('formatNumber2是什么', formatNumber);
    console.log([year, month, day].map(formatNumber));
    return [year, month, day].map(formatNumber).join('-');
  }
}
const formatNumber = n => {
    n = n.toString();
    return n[1] ? n : '0' + n;
}
const formatDateDay = (time, type) => {
  type = type || 1;

  var datetime = new Date();
  datetime.setTime(time * 1000);
  const year = datetime.getFullYear();
  const month = datetime.getMonth() + 1;
  const day = datetime.getDate();
  const hour = datetime.getHours();
  const minute = datetime.getMinutes();
  const second = datetime.getSeconds();

  if (type === 1) {
    console.log('formatNumber1是什么', formatNumber);
    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':');
  } else if (type === 2) {
    console.log('formatNumber2是什么', formatNumber);
    console.log([year, month, day].map(formatNumber));
    return [year, month, day].map(formatNumber).join('-');
  }
}
// 星星评分组件实现
const convertToStarsArray = (stars, num=5) => {
  let array = [];
  for (let i = 1; i <= num; i++) {
    if (i <= stars) {
      array.push(1);
    } else {
      array.push(0);
    }
  }
  return array;
}

// 获取当前零点时间的unix时间戳
const getUnixTimestamp = (date) => {
  if (date) {
    return Math.round(new Date(date).getTime() / 1000);
  }
  return Math.round(new Date().getTime() / 1000);
}

// 根据工种id获取工种的图像地址
const getWorkerTypeImg = (id) => {
  if (id) {
    return "/images/worker-type/wk_" + id + ".png";
  }
  return "/images/worker-type/wk_default.png";
}

// 自定义错误请求消息提示
const errorMessage = function(data) {
  if (data["status"] == 412) {
    if (typeof(data["responseJSON"]["message"]) === "string") {
      wx.showToast({
        title: data["responseJSON"]["message"]
      });
    } else if (typeof(data["responseJSON"]["message"]) === "object") {
      if (Array.isArray(data["responseJSON"]["message"])) {
        var oArray = [];
        for (var item in data["responseJSON"]["message"][0]) {
          oArray.push(data["responseJSON"]["message"][0][item]);
        }
        //return oArray[0].toString();
        wx.showToast({
          title: oArray[0].toString()
        });
      } else {
        var oArray = [];
        for (var item in data["responseJSON"]["message"]) {
          oArray.push(data["responseJSON"]["message"][item]);
        }
        //return oArray[0].toString();
        wx.showToast({
          title: oArray[0].toString()
        });
      }
    }
  } else if (data["status"] == 401) {
      
  } else {
    if (data["responseJSON"]) {
      wx.showToast({
        title: data["responseJSON"]["message"]
      });
    } else {
      wx.showToast({
        title: "请求错误，请重试"
      });
    }
  }
}

// 封装showModal，type为1表示雇主，2表示工人
const notVerifyModal = function(path) {
  uni.showModal({
    title: '还未入驻',
    content: '你还未入驻，暂时不能发布或者抢单或创建队伍，点击确定赶紧去入驻吧！',
    confirmColor: '#F94C48',
    success: function(res) {
     
      if (res.confirm) {
        uni.switchTab({
          url: path,
        })
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    }
  })
};
// 封装showModal，type为1表示雇主，2表示工人,这里是tabbar的方法
const notVerifyModalTabBar = function (path) {
  wx.showModal({
    title: '还未入驻',
    content: '你还未入驻，暂时不能发布或者抢单或创建队伍，点击确定赶紧去入驻吧！',
    confirmColor: '#F94C48',
    success: function (res) {

      if (res.confirm) {
        wx.switchTab({
          url: path,
        })
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    }
  })
};
const identityInformation = function (path) {
  wx.showModal({
    title: '温馨提示',
    content: '为方便客户更全面的了解您，让您接到更多的业务，请完善您的个人资料。',
    confirmColor: '#F94C48',
    success: function (res) {
      if (res.confirm) {
        wx.navigateTo({
          url: path,
        })
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    }
  })
}

// 检测对象是否有值
const isObjValid = function(obj) {
  for (let i in obj) {
  if (!obj[i]) return false;
  }
  return true;
};

// 检测对象是否有值，返回出错原因
const isObjValidDetail = function (obj) {
  for (let i in obj) {
    if (!obj[i]) return `${i}没有填写完整`
  }
  return 1;
};

const showMsg = function () {
  // wx.showModal({
  //   title: '提交失败',
  //   content: '请填写完带【图标】的"必填信息"后，再进行提交。',
  //   showCancel: false,
  //   confirmColor: '#f94c48',
  // })
};

const showModal = function (title, content, isCancel=false, success=()=>{}, fail=()=>{}) {
  wx.showModal({
    title: title,
    content: content,
    showCancel: isCancel,
    confirmColor: '#F94C48',
    success: (res) => {
        success
    },
    fail: (res) => {
      fail
    }
  })
}
/**
 * 生成富文本节点
 */
function generateRichTextNode(text) {
  let tempStr = text
  let richTextNode = []
  let leftBracketIndex = tempStr.indexOf('[')
  let rightBracketIndex = tempStr.indexOf(']')
  let countOfWord = 0
  Array.from(tempStr).map(item => {
    if (item != '[' && item != ']') {
      countOfWord++
    }
  })
  if (leftBracketIndex == -1 || rightBracketIndex == -1 || countOfWord == 0) {//没有emoji
    richTextNode.push({
      type: 'text',
      text: tempStr
    })
    return richTextNode
  }
  while (tempStr.length != 0) {
    leftBracketIndex = tempStr.indexOf('[')
    rightBracketIndex = tempStr.indexOf(']')
    if (leftBracketIndex == 0) { // 开头是[
      rightBracketIndex = tempStr.indexOf(']')
      if (rightBracketIndex == -1) {
        richTextNode.push({
          type: 'text',
          text: tempStr
        })
        tempStr = ''
      } else {
        let emojiName = tempStr.slice(0, rightBracketIndex + 1)
        if (emoji[emojiName]) { // 有效emoji
          richTextNode.push({
            name: 'img',
            attrs: {
              width: '30rpx',
              height: '30rpx',
              src: emoji[emojiName].img
            }
          })
        } else {//无效emoji
          richTextNode.push({
            type: 'text',
            text: emojiName
          })
        }
        tempStr = tempStr.substring(rightBracketIndex + 1, tempStr.length)
      }
    } else { // 开头不是[
      if (leftBracketIndex == -1) {// 最后全是文字
        richTextNode.push({
          type: 'text',
          text: tempStr.slice(0, tempStr.length)
        })
        tempStr = ''
      } else {
        richTextNode.push({
          type: 'text',
          text: tempStr.slice(0, leftBracketIndex)
        })
        tempStr = tempStr.substring(leftBracketIndex, tempStr.length + 1)
      }
    }
  }
  return richTextNode
}

/**
 * 处理图片富文本节点
 */
function generateImageNode(file) {
  let width = 0, height = 0
  if (file.w > 250) {
    width = 200
    height = file.h / (file.w / 200)
  } else {
    width = file.w
    height = file.h
  }
  let richTextNode = []
  richTextNode.push({
    name: 'img',
    attrs: {
      width: `${width}rpx`,
      height: `${height}rpx`,
      src: file.url
    }
  })
  return richTextNode
}

/**
 * 输出猜拳图片对象，用于生成富文本图片节点
 */
function generateFingerGuessImageFile(value) {
  let file = { w: 50, h: 50, url: '' }
  switch (value) {
    case 1:
      file.url = 'http://yx-web.nos.netease.com/webdoc/h5/im/play-1.png'
      break
    case 2:
      file.url = 'http://yx-web.nos.netease.com/webdoc/h5/im/play-2.png'
      break
    case 3:
      file.url = 'http://yx-web.nos.netease.com/webdoc/h5/im/play-3.png'
      break
    default:
      break
  }
  return file
}
module.exports = {
  getWorkerTypeImg: getWorkerTypeImg, //获取工种头像地址
  formatTime: formatTime,
  convertToStarsArray: convertToStarsArray,
  getUnixTimestamp: getUnixTimestamp,
  generateRichTextNode: generateRichTextNode,
  generateImageNode:generateImageNode,
  generateFingerGuessImageFile:generateFingerGuessImageFile,
  // wxLogin: wxLogin,
  notVerifyModal: notVerifyModal,
  notVerifyModalTabBar: notVerifyModalTabBar,
  formatDateDay: formatDateDay,
  errorMessage: errorMessage,
  isObjValid: isObjValid,
  isObjValidDetail: isObjValidDetail,
  showMsg: showMsg,
  showModal,
  identityInformation: identityInformation,
}